package com.scisoft.scan.control.enterdepot;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.data.enterdepot.EnterDepotOperator;
import com.scisoft.scan.data.enterdepot.EnterDepotOrderBean;
import com.scisoft.scan.data.enterdepot.EnterDepotOrderDetailBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.SysParameter;
import com.scisoft.scan.ws.WebServiceHelper_EnterDepot;

import java.util.ArrayList;
import java.util.List;

public class EnterDepotDetailActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ListView lv_data;
    private TextView bt_all;
    private TextView bt_undo;
    private TextView bt_done;
    private TextView tv_submit;
    private View v_all;
    private View v_undo;
    private View v_done;
    private ClearEditText et_bar;
    private List<EnterDepotOrderDetailBean> depotOrderDetailBeanList;
    private List<EnterDepotOrderDetailBean> currentList;
    private String currentflag = "1";//1 全部 2 待处理 3 已处理
    private EnterDepotOrderBean orderBean;
    private EnterDepotOrderDetailBean currentDetailBean;
    private String orderState;//0 未完成 1已完成

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_enter_depot_detail);

        currentList = new ArrayList<>();
        depotOrderDetailBeanList = new ArrayList<>();
        //参数传递
        Intent intent = getIntent();
        orderBean = (EnterDepotOrderBean) intent.getSerializableExtra("data");
        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setText(orderBean.orderNo);
        TextView tv_orderNo = findViewById(R.id.tv_orderNo);
        tv_orderNo.setText("操作人：" + orderBean.operator);
        TextView tv_orderRemark = findViewById(R.id.tv_orderRemark);
        tv_orderRemark.setText("备注："+orderBean.remark);
        //控件初始化
        lv_data = findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new ListViewClick());
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DEPOT_06();
            }
        });
        orderState = orderBean.orderState.contains("完成") ? "1" : "0";
        if (orderState.equals("1")) {
            tv_submit.setVisibility(View.INVISIBLE);
        } else {
            tv_submit.setVisibility(View.VISIBLE);
            //滑动
            setLeftScroll();
        }
        et_bar = findViewById(R.id.et_bar);
        bt_all = findViewById(R.id.bt_all);
        bt_undo = findViewById(R.id.bt_undo);
        bt_done = findViewById(R.id.bt_done);
        v_all = findViewById(R.id.v_all);
        v_undo = findViewById(R.id.v_undo);
        v_done = findViewById(R.id.v_done);
        //页签切换
        bt_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(EnterDepotDetailActivity.this);
            }
        });
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(EnterDepotDetailActivity.this);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(EnterDepotDetailActivity.this);
            }
        });
        setButton(bt_all);

        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //查询当前订单用户是否一致
        CommonUtil.showPress(this);
        QueryLastOperatorTask queryLastOperatorTask = new QueryLastOperatorTask(EnterDepotDetailActivity.this);
        queryLastOperatorTask.execute();
    }

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        QueryDepotOrder();
    }

    //左滑事件处理
    private float startX;
    private float startY;
    private float downX;
    private float downY;

    @SuppressLint("ClickableViewAccessibility")
    private void setLeftScroll() {
        lv_data.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        downX = event.getX();
                        downY = event.getY();
                        if (Math.abs(downY - startY) < Math.abs(downX - startX)) {
                            int position1 = lv_data.pointToPosition((int) startX, (int) startY);
                            int position2 = lv_data.pointToPosition((int) downX, (int) downY);
                            //从右向左鼠标移动超过20判断为左滑，并且每次滑动都在一行
                            if (startX - downX > 20 && position1 == position2)
                                //Toast.makeText(DepotDetailActivity.this, "左右" + position1, Toast.LENGTH_LONG).show();
                                if (position1 >= 0 && position1 < currentList.size()) {
                                    EnterDepotOrderDetailBean temp = currentList.get(position1);
                                    currentDetailBean = temp;
                                    //注意这里是列表传地址引用，才可以这么写。
                                    if (temp.ifOk.equals("0")) {
                                        temp.ifOk = "1";
                                        temp.notPickedCount = "0";
                                        temp.pickedCount = temp.partCount;
                                        DEPOT_04();//更新当前已处理
                                    } else {
                                        temp.ifOk = "0";
                                        temp.notPickedCount = temp.partCount;
                                        temp.pickedCount = "0";
                                        DEPOT_05();//更新未处理
                                    }
                                    QueryDepotOrder();
                                }
                            return true;
                        }
                        break;
                }
                return false;
            }
        });
    }

    //进入二级界面
    private class ListViewClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //弹窗输入数量
            if (position >= 0 && position < currentList.size()) {
                EnterDepotOrderDetailBean enterDepotOrderDetailBean = currentList.get(position);
                alert_edit(enterDepotOrderDetailBean);
            }
        }
    }

    //自定义弹出窗口
    private void alert_edit(final EnterDepotOrderDetailBean enterDepotOrderDetailBean) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_enterdepot, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        TextView tv_zms = (TextView) dialogView.findViewById(R.id.tv_zms);
        tv_zms.setText(String.valueOf(enterDepotOrderDetailBean.partCount));
        final TextView et_count = (TextView) dialogView.findViewById(R.id.et_count);
        TextView tv_equal = (TextView) dialogView.findViewById(R.id.tv_equal);
        tv_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //全部
                et_count.setText(String.valueOf(enterDepotOrderDetailBean.partCount));
                EnterDepotOrderDetailBean newData = enterDepotOrderDetailBean;
                newData.pickedCount = et_count.getText().toString();
                newData.notPickedCount = "0";
                DEPOT_07(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_none = (TextView) dialogView.findViewById(R.id.tv_none);
        tv_none.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清空
                et_count.setText("");
            }
        });
        TextView tv_ok = (TextView) dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                EnterDepotOrderDetailBean newData = enterDepotOrderDetailBean;
                newData.pickedCount = et_count.getText().toString();
                newData.notPickedCount = "0";
                DEPOT_07(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_all.getId()) {
            currentflag = "1";
            v_all.setVisibility(View.VISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_undo.getId()) {
            currentflag = "2";
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            currentflag = "3";
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
    }

    //绑定数据
    private void BindData(Context context) {
        //判断当前页签
        currentList.clear();
        if (currentflag.equals("1")) {
            for (int i = 0; i < depotOrderDetailBeanList.size(); i++) {
                currentList.add(depotOrderDetailBeanList.get(i));
            }
        } else if (currentflag.equals("2")) {
            for (int i = 0; i < depotOrderDetailBeanList.size(); i++) {
                EnterDepotOrderDetailBean temp = depotOrderDetailBeanList.get(i);
                if (temp.ifOk.equals("0")) {
                    currentList.add(temp);
                }
            }
        } else {
            for (int i = 0; i < depotOrderDetailBeanList.size(); i++) {
                EnterDepotOrderDetailBean temp = depotOrderDetailBeanList.get(i);
                if (temp.ifOk.equals("1")) {
                    currentList.add(temp);
                }
            }
        }
        int undo = 0;
        for (int i = 0; i < depotOrderDetailBeanList.size(); i++) {
            EnterDepotOrderDetailBean temp = depotOrderDetailBeanList.get(i);
            if (temp.ifOk.equals("0")) {
                undo++;
            }
        }
        int done = depotOrderDetailBeanList.size() - undo;
        //更新标题
        bt_all.setText("全部[" + depotOrderDetailBeanList.size() + "]");
        bt_undo.setText("待处理[" + undo + "]");
        bt_done.setText("已处理[" + done + "]");
        //更新数据
        EnterDepotDetailAdapter adapter = new EnterDepotDetailAdapter(currentList, context);
        lv_data.setAdapter(adapter);
    }

    //查询订单明细
    private void QueryDepotOrder() {
        CommonUtil.showPress(this);
        QueryDepotOrderTask QueryPackInfoTask = new QueryDepotOrderTask(EnterDepotDetailActivity.this);
        QueryPackInfoTask.execute();
    }

    //左滑将未处理的配件标记为已处理
    private void DEPOT_04() {

        DepotPartOrderTask DepotPartOrderTask = new DepotPartOrderTask(EnterDepotDetailActivity.this);
        DepotPartOrderTask.execute();
    }

    //左滑将已处理的配件标记为未处理
    private void DEPOT_05() {
        DepotUnPartOrderTask DepotUnPartOrderTask = new DepotUnPartOrderTask(EnterDepotDetailActivity.this);
        DepotUnPartOrderTask.execute();
    }

    //提交完成
    private void DEPOT_06() {
        CommonUtil.showPress(this);
        CompletePartOrderTask completePartOrderTask = new CompletePartOrderTask(EnterDepotDetailActivity.this);
        completePartOrderTask.execute();
    }

    //手工录入数量
    private void DEPOT_07(EnterDepotOrderDetailBean enterDepotOrderDetailBean ) {

        UpdateDepotPartOrderTask updateDepotPartOrderTask = new UpdateDepotPartOrderTask(EnterDepotDetailActivity.this, enterDepotOrderDetailBean);
        updateDepotPartOrderTask.execute();
    }

    //查询订单明细服务
    class QueryDepotOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryDepotOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //设置当前最后操作的用户
                EnterDepotOperator operator = new EnterDepotOperator();
                if (SysParameter.userInfo != null) {
                    operator.operatorName = SysParameter.userInfo.userName;
                }
                msg = WebServiceHelper_EnterDepot.ENTER_10(orderBean.orderId, operator);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_EnterDepot.ENTER_03(orderBean.orderId);
                    msg = "成功";
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //左滑一键处理完当前配件服务
    class DepotPartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        DepotPartOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_EnterDepot.ENTER_04(currentDetailBean.dtlId);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_EnterDepot.ENTER_03(orderBean.orderId);
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //左滑一键取消当前配件服务
    class DepotUnPartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        DepotUnPartOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_EnterDepot.ENTER_05(currentDetailBean.dtlId);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_EnterDepot.ENTER_03(orderBean.orderId);
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //手工输入拣货数量并且提交
    class UpdateDepotPartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private EnterDepotOrderDetailBean enterDepotOrderDetailBean;

        UpdateDepotPartOrderTask(Context context,EnterDepotOrderDetailBean enterDepotOrderDetailBean ) {
            super();
            mcontext = context;
            this.enterDepotOrderDetailBean = enterDepotOrderDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_EnterDepot.ENTER_07(orderBean.orderId,enterDepotOrderDetailBean);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_EnterDepot.ENTER_03(orderBean.orderId);
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //全部拣货提交服务
    class CompletePartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CompletePartOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_EnterDepot.ENTER_06(orderBean.orderId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //获取当前订单最后操作员服务
    class QueryLastOperatorTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        EnterDepotOperator operator;

        QueryLastOperatorTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                operator = WebServiceHelper_EnterDepot.ENTER_09(orderBean.orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                boolean ok = false;

                if (operator.operatorName == null || "".equals(operator.operatorName)) {
                    //当前订单无人操作
                    ok = true;
                }
                //判断最后操作用户跟当前用户是否一致
                if (SysParameter.userInfo != null && operator.operatorName.equals(SysParameter.userInfo.userName)) {
                    //当前订单是本人
                    ok = true;
                }
                //test
                //ok = true;
                //test
                if (!ok) {
                    //当前订单是其它人操作
                    AlertDialog alertDialog = new AlertDialog.Builder(EnterDepotDetailActivity.this)
                            //.setTitle("这是标题")
                            .setMessage("当前订单的最后操作员是" + operator.operatorName + ",是否继续操作?")
                            //.setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    QueryDepotOrder();
                                }
                            })

                            .setNegativeButton("否", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    finish();
                                }
                            })
                            .create();
                    alertDialog.show();

                } else {
                    //当前订单是本人或者无人操作
                    QueryDepotOrder();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

}
